<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="queryParams.roleName" placeholder="请输入角色名称" clearable style="width: 240px" />
        </el-form-item>
        <el-form-item label="权限字符" prop="roleKey">
          <el-input v-model="queryParams.roleKey" placeholder="请输入权限字符" clearable style="width: 240px" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="角色状态" clearable style="width: 240px">
            <el-option label="启用" value="0" />
            <el-option label="禁用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery"><el-icon><Search /></el-icon>搜索</el-button>
          <el-button @click="resetQuery"><el-icon><Refresh /></el-icon>重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <el-card class="table-container">
      <template #header>
        <div class="card-header">
          <span>角色列表</span>
          <div class="right">
            <el-button type="primary" @click="handleAdd"><el-icon><Plus /></el-icon>新增</el-button>
            <el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete">
              <el-icon><Delete /></el-icon>批量删除
            </el-button>
            <el-button @click="handleExport"><el-icon><Download /></el-icon>导出</el-button>
          </div>
        </div>
      </template>

      <!-- 角色表格 -->
      <el-table
        v-loading="loading"
        :data="roleList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="角色编号" prop="roleId" width="100" />
        <el-table-column label="角色名称" prop="roleName" :show-overflow-tooltip="true" />
        <el-table-column label="权限字符" prop="roleKey" :show-overflow-tooltip="true" />
        <el-table-column label="显示顺序" prop="sortOrder" width="100" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="0"
              :inactive-value="1"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
        <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button link type="primary" @click="handleDelete(scope.row)">删除</el-button>
            <el-dropdown>
              <el-button link type="primary">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleAuthUser(scope.row)">分配用户</el-dropdown-item>
                  <el-dropdown-item @click="handleDataScope(scope.row)">数据权限</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改角色对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="roleForm" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="权限字符" prop="roleKey">
          <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
        </el-form-item>
        <el-form-item label="角色顺序" prop="roleSort">
          <el-input-number v-model="form.roleSort" :min="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-tree
            ref="menuTreeRef"
            :data="menuOptions"
            show-checkbox
            node-key="id"
            :props="defaultProps"
            empty-text="加载中，请稍候"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Plus, Delete, Download, Refresh, ArrowDown } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Pagination from '@/components/Pagination/index.vue'
import { listRole, getRole, addRole, updateRole, deleteRole, batchDeleteRole, exportRole } from '@/api/role'

// 加载状态
const loading = ref(false)
// 选中ID数组
const selectedIds = ref([])
// 总条数
const total = ref(0)

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  roleName: undefined,
  roleKey: undefined,
  status: undefined
})

// 表单参数
const form = ref({
  roleId: undefined,
  roleName: undefined,
  roleKey: undefined,
  roleSort: 0,
  status: 0,
  menuIds: [],
  remark: undefined
})

// 树形配置
const defaultProps = {
  children: 'children',
  label: 'label'
}

// 表单校验规则
const rules = {
  roleName: [
    { required: true, message: '角色名称不能为空', trigger: 'blur' }
  ],
  roleKey: [
    { required: true, message: '权限字符不能为空', trigger: 'blur' }
  ],
  roleSort: [
    { required: true, message: '角色顺序不能为空', trigger: 'blur' }
  ]
}

// 对话框状态
const dialog = reactive({
  visible: false,
  title: ''
})

// 角色表格数据
const roleList = ref([])

// 菜单树数据
const menuOptions = ref([
  {
    id: 1,
    label: '系统管理',
    children: [
      {
        id: 2,
        label: '用户管理'
      },
      {
        id: 3,
        label: '角色管理'
      },
      {
        id: 4,
        label: '菜单管理'
      }
    ]
  },
  {
    id: 5,
    label: '车辆管理',
    children: [
      {
        id: 6,
        label: '车辆列表'
      },
      {
        id: 7,
        label: '车辆检查'
      }
    ]
  }
])

// 在组件挂载时获取数据
onMounted(() => {
  getList()
})

// 获取角色列表
function getList() {
  loading.value = true
  listRole(queryParams.value).then(res => {
    console.log('角色列表响应数据:', res)
    // 处理不同的后端返回格式
    if (Array.isArray(res)) {
      roleList.value = res
      total.value = res.length
    } else if (res.rows) {
      roleList.value = res.rows
      total.value = res.total || res.rows.length
    } else if (res.data) {
      if (Array.isArray(res.data)) {
        roleList.value = res.data
        total.value = res.data.length
      } else if (res.data.rows) {
        roleList.value = res.data.rows
        total.value = res.data.total || res.data.rows.length
      } else {
        roleList.value = [res.data]
        total.value = 1
      }
    } else {
      roleList.value = []
      total.value = 0
    }
    loading.value = false
  }).catch(err => {
    console.error('获取角色列表失败:', err)
    roleList.value = []
    total.value = 0
    loading.value = false
  })
}

// 表单重置
function resetForm() {
  form.value = {
    roleId: undefined,
    roleName: undefined,
    roleKey: undefined,
    roleSort: 0,
    status: 0,
    menuIds: [],
    remark: undefined
  }
}

// 搜索按钮操作
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

// 重置按钮操作
function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    roleName: undefined,
    roleKey: undefined,
    status: undefined
  }
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  selectedIds.value = selection.map(item => item.roleId)
}

// 新增按钮操作
function handleAdd() {
  resetForm()
  dialog.visible = true
  dialog.title = '添加角色'
}

// 修改按钮操作
function handleUpdate(row) {
  resetForm()
  const roleId = row.roleId || row.id
  console.log('获取角色详情, ID:', roleId)
  // 调用获取详情的 API
  getRole(roleId).then(res => {
    console.log('角色详情响应:', res)
    let roleData = res
    if (res.data) {
      roleData = res.data
    }
    // 处理后端返回的数据格式
    form.value = {
      roleId: roleData.roleId || roleData.id,
      roleName: roleData.roleName,
      roleKey: roleData.roleKey,
      roleSort: roleData.roleSort || roleData.sortOrder,
      status: roleData.status,
      remark: roleData.remark
    }
    dialog.visible = true
    dialog.title = '修改角色'
  }).catch(err => {
    console.error('获取角色详情失败:', err)
    ElMessage.error('获取角色详情失败')
  })
}

// 提交按钮
function submitForm() {
  // 准备提交数据，确保字段名匹配后端
  const submitData = {
    roleId: form.value.roleId,
    roleName: form.value.roleName,
    roleKey: form.value.roleKey,
    sortOrder: form.value.roleSort,
    status: form.value.status,
    remark: form.value.remark
  }
  
  if (submitData.roleId) {
    updateRole(submitData).then(() => {
      ElMessage.success('修改成功')
      dialog.visible = false
      getList()
    }).catch(err => {
      console.error('修改角色失败:', err)
      ElMessage.error('修改失败')
    })
  } else {
    addRole(submitData).then(() => {
      ElMessage.success('新增成功')
      dialog.visible = false
      getList()
    }).catch(err => {
      console.error('新增角色失败:', err)
      ElMessage.error('新增失败')
    })
  }
}

// 删除按钮操作
function handleDelete(row) {
  const roleId = row.roleId || row.id || selectedIds.value
  ElMessageBox.confirm('是否确认删除角色编号为"' + roleId + '"的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteRole(roleId).then(() => {
      ElMessage.success('删除成功')
      getList()
    }).catch(err => {
      console.error('删除角色失败:', err)
      ElMessage.error('删除失败')
    })
  }).catch(() => {})
}

// 批量删除操作
function handleBatchDelete() {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择至少一条记录')
    return
  }
  
  const roleIds = selectedIds.value.join(',')
  ElMessageBox.confirm('是否确认批量删除所选角色?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    batchDeleteRole(roleIds).then(() => {
      ElMessage.success('批量删除成功')
      getList()
    }).catch(err => {
      console.error('批量删除失败:', err)
      ElMessage.error('批量删除失败')
    })
  }).catch(() => {})
}

// 导出按钮操作
function handleExport() {
  ElMessageBox.confirm('是否确认导出所有角色数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    exportRole().then(res => {
      let data = res.data
      if (Array.isArray(data)) {
        // 处理导出逻辑
        ElMessage.success('导出成功')
      } else if (data.data && Array.isArray(data.data)) {
        // 处理嵌套数据
        ElMessage.success('导出成功')
      } else {
        ElMessage.warning('没有数据可导出')
      }
    }).catch(err => {
      console.error('导出失败:', err)
      ElMessage.error('导出失败')
    })
  }).catch(() => {})
}

// 状态修改
function handleStatusChange(row) {
  // 这里应该调用修改状态的 API
  ElMessage.success('状态修改成功')
}

// 分配用户
function handleAuthUser(row) {
  // 这里应该跳转到用户分配页面或打开用户分配弹窗
  ElMessage.info('用户分配功能正在开发中')
}

// 设置数据权限
function handleDataScope(row) {
  // 这里应该打开数据权限设置弹窗
  ElMessage.info('数据权限功能正在开发中')
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 15px;
}

.table-container {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .right {
    display: flex;
    gap: 10px;
  }
}
</style> 